/**
 * Copyright：2020，TLF工作室。
 */
package com.cqeec.netdisc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqeec.netdisc.model.User;
import com.cqeec.netdisc.service.UserService;
import com.google.code.kaptcha.Constants;

/**
 * 登录控制器。
 * 
 * @author 唐礼飞
 * 
 * @date 2020-10-19 10:19:46
 *
 */
@Controller
public class LoginController {

	@Autowired
	private UserService userService;

	@RequestMapping({ "/", "/login" })
	public String gotoLoginPage() {
		return "login";
	}

	@RequestMapping("/user/login")
	@ResponseBody
	public Map<String, Object> login(HttpSession session, String name, String password, String captcha) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 验证码验证
		if (captcha == null || "".equals(captcha)) {
			map.put("code", 1);
			map.put("message", "请输入验证码！");
			return map;
		}
		Object obj = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if (obj == null) {
			map.put("code", 2);
			map.put("message", "验证码已经失效，请刷新页面重新登录！");
			return map;
		}
		String code = (String) obj;
		if (!code.equals(captcha)) {
			map.put("code", 3);
			map.put("message", "验证码输入错误！");
			return map;
		}
		// 用户验证
		if (name == null || "".equals(name)) {
			map.put("code", 4);
			map.put("message", "请输入用户名！");
			return map;
		}
		if (password == null || "".equals(password)) {
			map.put("code", 5);
			map.put("message", "请输入用户密码！");
			return map;
		}
		User user = userService.login(name, password);
		if (user == null) {
			map.put("code", 6);
			map.put("message", "登录失败，用户名或密码错误！");
		} else {
			session.setAttribute("user", user);
			map.put("code", 0);
			map.put("message", "用户登录成功！");
		}
		return map;
	}

	@RequestMapping("/user/exit")
	public String exit(HttpSession session) {
		session.removeAttribute("user");
		return "redirect:/login";
	}

}
